import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入二级路由模块
import Home from '@/views/layout/home.vue'
import Category from '@/views/layout/category.vue'
import Cart from '@/views/layout/cart.vue'
import User from '@/views/layout/user.vue'
import store from '@/store'

// 导入一级路由模块
const Login = () => import('@/views/login/index.vue')
const Layout = () => import('@/views/layout/index.vue')
const Search = () => import('@/views/search/index.vue')
const Myorder = () => import('@/views/myorder/index.vue')
const Pay = () => import('@/views/pay/index.vue')
const Prodetail = () => import('@/views/prodetail/index.vue')
const SearchList = () => import('@/views/search/list.vue')
const AddressList = () => import('@/views/pay/adderssList.vue')
const AddAddress = () => import('@/views/pay/addAddress.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    name: 'layout',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'home',
        component: Home
      },
      {
        path: '/category',
        name: 'category',
        component: Category
      },
      {
        path: '/cart',
        name: 'cart',
        component: Cart
      },
      {
        path: '/user',
        name: 'user',
        component: User
      }

    ]
  },
  {
    path: '/search',
    name: 'search',
    component: Search
  },
  {
    path: '/order/list',
    name: 'myorder',
    component: Myorder
  },
  {
    path: '/pay',
    name: 'pay',
    component: Pay
  },
  {
    path: '/prodetail/:goods_id',
    name: 'prodetail',
    component: Prodetail
  },
  {
    path: '/searchlist',
    name: 'searchlist',
    component: SearchList
  },
  {
    path: '/addressList',
    name: 'addressList',
    component: AddressList
  },
  {
    path: '/searchlist',
    name: 'searchlist',
    component: SearchList
  },
  {
    path: '/addAddress',
    name: 'addAddress',
    component: AddAddress
  }
]

// 需要权限才能访问的页面
const pages = ['/pay', '/order/list']
const router = new VueRouter({
  routes
})

// 导航前置守卫： 当访问到需要权限的页面时可以配置导航守卫强制跳转
router.beforeEach((to, from, next) => {
  // to: 到哪里去
  // from： 从哪里来
  // next： 是否放行
  // console.log(to.path, from, next)
  // 判断现在需要跳转到的页面是不是权限页面
  if (!pages.includes(to.path)) {
    // console.log('cscc')
    next()
    return
  }
  const token = store.state.user.userInfo.token
  console.log(token)
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
